package com.assistant.wechat.controller;

import com.assistant.common.DateUtil;
import com.assistant.wechat.pojo.WXSessionModel;
import com.assistant.wechat.pojo.WxUser;
import com.assistant.wechat.service.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class WXLoginController {

    @Autowired
    private WxUserService wxUserService;

    private WXSessionModel wxSessionModel = null;

    @PostMapping("/wxLogin")
    public ResponseEntity<Map<String, Object>> wxLogin(@RequestParam Map<String,String> params)  {
        WXSessionModel login = wxSessionModel;
        System.out.println(params);
        String openid = login.getOpenid();
        System.out.println(params.get("gender"));

        WxUser user = new WxUser();
        user.setCreate_time(DateUtil.dataFormatUtil(new Date()));
        user.setOpenid(openid);
        user.setCity(params.get("city"));
        user.setGender(Integer.valueOf(params.get("gender")));
        user.setAvatar_url(params.get("avatarUrl"));
        user.setNick_name( params.get("nickName"));
        user.setAuth(0);
        wxUserService.saveUser(user);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("msg", "登录成功");
        map.put("item", user);
        return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
    }

    @GetMapping("/isLogin")
    public ResponseEntity<Map<String, Object>> isLogin(String code) {
        WXSessionModel login = wxUserService.login(code);
        wxSessionModel = login;
        String openid = login.getOpenid();
        String session_key = login.getSession_key();
        List<WxUser> wxUsers = wxUserService.isLogin(openid);
        Map<String, Object> param = new HashMap<>();
        ResponseEntity<Map<String, Object>> mapResponseEntity = null;
        if (wxUsers.size()==1) {
            param.put("flag", "true");
            param.put("msg", "已登录");
            param.put("item", wxUsers.get(0));
            param.put("session_key", session_key);
        } else {
            param.put("flag", "false");
            param.put("msg", "未登录");
        }
        mapResponseEntity = new ResponseEntity<Map<String, Object>>(param, HttpStatus.OK);
        return mapResponseEntity;
    }
}
